import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/product_provider.dart';
import '../../utils/G.dart';
import 'detail/product_swiper.dart';
import 'detail/product_description.dart';
import 'detail/product_bottom_menu.dart';
import 'detail/product_spec.dart';

import '../../providers/user_provider.dart';

class ProductDetail extends StatefulWidget {
  String id;
  ProductDetail({Key? key, required String this.id}) : super(key: key);

  @override
  _ProductDetailState createState() => _ProductDetailState();
}

class _ProductDetailState extends State<ProductDetail> {
  Map detail = {};
  Map _userInfo = {};
  bool _isLogin = false;
  Widget _favoriteIcon = const Icon(Icons.favorite_border);
  var _futureInstance;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _futureInstance = G.api.product.detail(id: widget.id);
  }

  @override
  Widget build(BuildContext context) {
    _userInfo = context.read<UserProvider>().userInfo;
    _isLogin = context.read<UserProvider>().isLogin;

    return Scaffold(
      appBar: AppBar(
        title: const Text('商品详情'),
        centerTitle: true,
        actions: [
          InkWell(
            onTap: () {
              G.router.navigateTo(context, '/');
            },
            child: const Icon(Icons.home),
          ),
          const SizedBox(
            width: 10,
          )
        ],
      ),
      body: FutureBuilder(
          future: _futureInstance,
          builder: (context, snapshot) {
            // print('商品详情 - builder');
            if (snapshot.hasData) {
              var res = snapshot.data as Map;
              if (res['status'] == 200) {
                detail = res['data'];

                // 将商品详情信息，赋值到 ProductProvider 中。
                context.read<ProductProvider>().initProduct(detail);

                return ListView(
                  shrinkWrap: true,
                  children: [
                    // 图片轮播
                    _renderProductSwiper(),

                    // 商品标题
                    _renderProductTitle(),

                    // 商品价格
                    _renderProductPrice(),

                    // 商品规格
                    detail['productAttr'].length > 0
                        ? ProductSpec()
                        : Container(),

                    // 商品详情
                    ProductDescription(detail: detail)
                  ],
                );
              } else {
                // 报错
              }
            } else if (snapshot.hasError) {
              return Center(
                child: Text("${snapshot.error}"),
              );
            }

            return G.loader();
          }),
      bottomNavigationBar: const ProductBottomMenu(),
    );
  }

  Widget _renderProductSwiper() {
    return Container(
      height: 400,
      child: ProductSwiper(swiperlist: detail['storeInfo']['slider_image']),
    );
  }

  Widget _renderProductTitle() {
    return Container(
        margin: const EdgeInsets.all(10.0),
        child: Text(
          detail['storeInfo']['store_name'].toString(),
          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
          overflow: TextOverflow.ellipsis,
        ));
  }

  Widget _renderProductPrice() {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 0, 10, 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text("￥ " + detail['storeInfo']['price'].toString(),
              style: const TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.w500,
                  color: Colors.red)),
          Text("￥ " + detail['storeInfo']['ot_price'].toString(),
              style: const TextStyle(
                  fontSize: 16, decoration: TextDecoration.lineThrough)),
          Text(detail['storeInfo']['fsales'].toString() + " 已购",
              style: const TextStyle(
                fontSize: 16,
              )),

          // 收藏菜单
          _isLogin
              ? InkWell(
                  onTap: () async {
                    if (detail['storeInfo']['userCollect'] == true) {
                      // 取消收藏
                      var res =
                          await G.api.favorite.del(detail['storeInfo']['id']);
                      if (res['status'] == 200) {
                        setState(() {
                          _favoriteIcon = const Icon(Icons.favorite_border);
                          detail['storeInfo']['userCollect'] = false;
                        });
                      }
                    } else {
                      // 添加收藏
                      var res =
                          await G.api.favorite.add(detail['storeInfo']['id']);
                      if (res['status'] == 200) {
                        setState(() {
                          _favoriteIcon =
                              const Icon(Icons.favorite, color: Colors.red);
                          detail['storeInfo']['userCollect'] = true;
                        });
                      }
                    }
                  },
                  child: _favoriteIcon)
              : Container()
        ],
      ),
    );
  }
}
